package com.itheima.stargraph.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.itheima.stargraph.pojo.User;
import com.itheima.stargraph.utils.JWTUtils;
import com.itheima.stargraph.utils.UserThreadlocalUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录校验拦截器
 *
 * @Author mr.wu
 * @Date 2025-6-9 14:38
 */
@Component
public class UserInterceptor implements HandlerInterceptor {

    /**
     * 拦截的具体逻辑：验证是否携带有效Token
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 判断目标资源是否controller资源，非相应资源则放行
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }

        //2. 获取请求头中的令牌
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);

        //3. 如果为空，则响应401
        if(StrUtil.isBlank(token)) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            throw new RuntimeException("请登录");
        }

        //4. 解析Token，解析失败响应401
        boolean result = JWTUtils.verify(token);
        if(!result) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            throw new RuntimeException("请登录");
        }

        //5. 解析成功，设置用户信息到ThreadLocal中
        User user = JWTUtils.getUser(token);
        UserThreadlocalUtils.setUser(user);

        //6. 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadlocalUtils.remove();
    }
}
